<template>
  <div class="app">
      <input type="file" ref="fileInput" @change="handleFileChange" style="display: none">
      <button class="button1" @click="selectImage">选择图片</button>
      <button class="button2" @click="extractInfo">提取信息</button>
      <button class="button3" @click="judgeAuthenticity">判断真伪</button>
      <div>
        <img v-if="imageUrl" :src="imageUrl" alt="Selected Image" style="max-width: 500px; margin-top: 20px;">
      </div>
      <div v-if="showForm">
          <div>
              <label for="invoiceCode">发票代码:</label>
              <input type="text" id="invoiceCode" v-model="invoiceCode">
          </div>
          <div>
              <label for="invoiceNumber">发票编号:</label>
              <input type="text" id="invoiceNumber" v-model="invoiceNumber">
          </div>
          <div>
              <label for="issueDate">开票日期:</label>
              <input type="text" id="issueDate" v-model="issueDate">
          </div>
          <div>
              <label for="verificationCode">校验码:</label>
              <input type="text" id="verificationCode" v-model="verificationCode">
          </div>
          <div>
              <label for="totalAmount">总金额:</label>
              <input type="text" id="totalAmount" v-model="totalAmount">
          </div>
      </div>
      <div v-if="selectedImagePath">已选择图片: {{ selectedImagePath }}</div>
      <div v-if="extractedData">提取信息结果: {{ JSON.stringify(extractedData) }}</div>
      <div v-if="authenticityResult!== null">判断结果: {{ authenticityResult? '真' : '假' }}</div>
      <div v-if="verificationResult">查验结果: {{ verificationResult }}</div>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import axios from 'axios';

const fileInput = ref(null);
const selectedImagePath = ref('');
const extractedData = ref(null);
const authenticityResult = ref(null);
const imageUrl = ref('');
const showForm = ref(false);
const invoiceCode = ref('');
const invoiceNumber = ref('');
const issueDate = ref('');
const verificationCode = ref('');
const totalAmount = ref('');
const errorMessage = ref('');

const selectImage = () => {
  fileInput.value.click();
};

const handleFileChange = (e) => {
  const file = e.target.files[0];
  if (file) {
      const allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
      if (!allowedTypes.includes(file.type)) {
          errorMessage.value = '请选择有效的图片文件（JPEG、PNG、GIF）';
          console.error(errorMessage.value);
          return;
      }
      selectedImagePath.value = file.name;
      const reader = new FileReader();
      reader.onload = (event) => {
          imageUrl.value = event.target.result;
      };
      reader.readAsDataURL(file);
      showForm.value = true;
  }
};

const extractInfo = async () => {
  errorMessage.value = '';
  if (selectedImagePath.value) {
      const file = fileInput.value.files[0];
      if (!file) {
          errorMessage.value = '未正确获取选择的文件，请重试';
          console.error(errorMessage.value);
          return;
      }

      const formData = new FormData();
      formData.append('file', file);

      try {
          const response = await axios.post('http://127.0.0.1:5000/api/extract_info', formData, {
              headers: {
                  'Content-Type': 'multipart/form-data'
              },
              timeout: 5000 // 设置请求超时时间为5秒
          });
          if (response.status >= 200 && response.status < 300) {
              const data = response.data;
              console.log('提取信息结果:', data);
              if (typeof data === 'object' && data!== null) {
                  extractedData.value = data;
                  invoiceCode.value = data['发票代码'] || '';
                  invoiceNumber.value = data['发票号码'] || '';
                  issueDate.value = data['开票日期'] || '';
                  verificationCode.value = data['校验码'] || '';
                  totalAmount.value = data['小写金额'] || '';
              } else {
                  errorMessage.value = '接收到的数据不是有效的对象格式，请稍后重试';
                  console.error(errorMessage.value);
              }
          } else {
              const errorData = response.data;
              let errorMsg = `服务器响应状态码异常: ${response.status}`;
              if (errorData && errorData.error) {
                  errorMsg = `服务器错误: ${errorData.error}`;
              }
              errorMessage.value = errorMsg;
              console.error(errorMessage.value);
          }
      } catch (error) {
          if (error.code === 'ECONNABORTED') {
              errorMessage.value = '请求超时，请稍后重试';
          } else if (error.code === 'ERR_NETWORK') {
              errorMessage.value = '网络连接失败，请检查网络设置';
          } else {
              errorMessage.value = '提取信息出错，请稍后重试';
          }
          console.error('提取信息出错:', error);
          if (error.response) {
              console.error('服务器响应状态:', error.response.status);
              console.error('服务器响应数据:', error.response.data);
          }
      }
  } else {
      errorMessage.value = '请先选择图片';
      console.error(errorMessage.value);
  }
};

const judgeAuthenticity = async () => {
  try {
    const response = await axios.post('http://127.0.0.1:5000/api/check_invoice', {
      invoiceCode: invoiceCode.value,
      invoiceNumber: invoiceNumber.value,
      issueDate: issueDate.value,
      verificationCode: verificationCode.value,
      totalAmount: totalAmount.value
    });
    if (response.status === 200) {
      const result = response.data;
      console.log('判断结果:', result);
      // 根据后端返回的具体查验信息判断发票真伪，并更新查验结果显示
      if (result[VerifyMessage] === "查验成功发票一致") {
        verificationResult.value = '发票为真';
        authenticityResult.value = true;
      } else if (result[VerifyMessage] === "查验成功，发票不一致") {
        verificationResult.value = '发票为假';
        authenticityResult.value = false;
      } else {
        verificationResult.value = '查验结果异常，请检查查验信息';
        authenticityResult.value = null;
      }
    }
  } catch (error) {
    console.error('判断真伪出错:', error);
    alert('判断真伪出错，请稍后重试');
    verificationResult.value = '判断真伪出错，请稍后重试';
    authenticityResult.value = null;
  }
};
</script>

<style scoped>
.button1 {
  background-color: #71b9e5;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 5px;
  cursor: pointer;
  margin-left: 10px;
}

.button2 {
  background-color: #40a0a5;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 5px;
  cursor: pointer;
  margin-left: 10px;
}

.button3 {
  background-color: #339584;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 5px;
  cursor: pointer;
  margin-left: 10px;
}

div {
  margin: 10px 0;
}

label {
  display: inline-block;
  width: 100px;
}

input {
  padding: 5px;
  border: 1px solid #ccc;
  border-radius: 3px;
}
</style>